package org.web.ssm.service.impl;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.web.ssm.dao.OrderDetailMapper;
import org.web.ssm.dao.UserMapper;
import org.web.ssm.dto.StatisticsModel;
import org.web.ssm.exception.BaseException;
import org.web.ssm.exception.OrderException;
import org.web.ssm.model.OrderDetail;
import org.web.ssm.model.Topic;
import org.web.ssm.model.User;
import org.web.ssm.model.queryVo.BaseQuery;
import org.web.ssm.model.wechatModel.Statis;
import org.web.ssm.service.IOrderService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by LUOLIANG on 2016/6/13.
 */
@Service
public class OrderServiceImpl implements IOrderService {
    private Logger logger = LogManager.getLogger(OrderServiceImpl.class);
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public OrderDetail getOrderByid(String orderid) {
        return orderDetailMapper.selectByPrimaryKey(orderid);
    }

    @Override
    public List<OrderDetail> getAllOrderByUser(String userid, String type) {
        return orderDetailMapper.selectAllByUser(userid, type);
    }

    @Override
    public void insertOrder(OrderDetail orderDetail) {
        try {
            int res = orderDetailMapper.insertOrder(orderDetail);
            if (res == 1) {
                String money = String.valueOf(orderDetail.getCharges());
                if (orderDetail.getIncometype().equals("支出")) {
                    money = "-" + money;
                }
                orderDetailMapper.updateUserMoney(orderDetail.getUser().getUserid(), money);
            } else {
                throw new OrderException("插入订单失败");
            }
        } catch (OrderException e) {
            throw e;
        } catch (Exception e1) {
            logger.error(e1.getMessage());
            throw new BaseException("插入订单操作异常：" + e1.getMessage());
        }
    }

    @Transactional
    public String messageOrder(String str, String incometype, String ToUserName) {
        // 根据正则表达式取出字符串中的数字
        Pattern p = Pattern.compile("[0-9]");
        Matcher m = p.matcher(str);

        StringBuilder sb = new StringBuilder();
        int n = 0;
        while (m.find()) {
            if (n == 0 && m.group() == "0") {
                continue;
            } else {
                sb.append(m.group());
            }
            n++;
        }
        User user = userMapper.selectByOpenid(ToUserName);
        OrderDetail orderDetail = new OrderDetail(user, incometype, "日常生活", str, Double.valueOf(sb.toString()), new Date());

        try {
            if (!sb.toString().equals("")) {
                insertOrder(orderDetail);
                return new StringBuffer().append("===总共" + getAllOrderByUser(user.getUserid(), "").size() + "笔账单===\n" + "【" + incometype + "】 " + sb.toString() + "元\n" + "【类别】 " + "日常生活\n" + "【备注】 " + str).toString();
            } else {
                return "输入有误，请重新输入";
            }
        } catch (OrderException e) {
            throw e;
        } catch (Exception e1) {
            logger.error(e1.getMessage());
            throw new BaseException("插入订单操作异常：" + e1.getMessage());
        }
    }

    @Override
    public StatisticsModel getStatisData(String userid) {
        try {
            List<Statis> weeklist = orderDetailMapper.selectSumBytime(userid, "week");
            List<Statis> monlist = orderDetailMapper.selectSumBytime(userid, "mon");

            return new StatisticsModel(weeklist, monlist);
        } catch (OrderException e) {
            throw e;
        } catch (Exception e1) {
            logger.error(e1.getMessage());
            throw new BaseException("getStatisData操作异常：" + e1.getMessage());
        }
    }

    @Override
    public BaseQuery<OrderDetail> orderlistByUser(int pageSize, int pageCurrent, int userId) {
        BaseQuery<OrderDetail> topicQuery = new BaseQuery<OrderDetail>();
        topicQuery.setPageSize(pageSize);
        topicQuery.setMaxRow(pageSize * pageCurrent + 1);
        topicQuery.setMinRow(pageSize * (pageCurrent - 1));
        topicQuery.setCurrentPage(pageCurrent);
        topicQuery.setIntkeyWords(userId);
        topicQuery.setResults(orderDetailMapper.orderlistByUser(topicQuery));
        topicQuery.setTotalRow(orderDetailMapper.getCount(topicQuery));
        int totalPage = topicQuery.getTotalRow() % topicQuery.getPageSize() == 0 ? topicQuery.getTotalRow() / topicQuery.getPageSize() : topicQuery.getTotalRow() / topicQuery.getPageSize() + 1;
        topicQuery.setTotalPage(totalPage);
        return topicQuery;
    }
}
